package com.yingdong.gateserver.net;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yingdong.gateserver.innter.message.ClearOnlineUserMessage;
import com.yingdong.gateserver.innter.message.SessionConnectedMessage;
import com.yingdong.gateserver.opcode.Dispatcher;
import com.yingdong.utils.IdFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

public class GateServerHandlerNetty4 extends ChannelInboundHandlerAdapter {
	static Log logger = LogFactory.getLog(GateServerHandlerNetty4.class);
	private final AttributeKey<Integer> CHANNELID = AttributeKey.valueOf("CHANNELID");

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		int id = IdFactory.nextInt();
		Attribute<Integer> attribute = ctx.attr(CHANNELID);
		attribute.set(id);
		Channel channel = ctx.channel();
		Dispatcher.sessionMap.put(id, new GameSession(id, channel));
		try {
			new SessionConnectedMessage(id, ctx.channel().remoteAddress() == null ? "" : ctx.channel().remoteAddress().toString()).sendToSceneServer();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			logger.error("", e1);
		}
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Attribute<Integer> attribute = ctx.attr(CHANNELID);
		int id = attribute.get();
		if (Dispatcher.sessionMap.containsKey(id)) {
			new ClearOnlineUserMessage(id).sendToSceneServer();
			Dispatcher.sessionMap.remove(id);
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buffer = (ByteBuf) msg;
		Attribute<Integer> attribute = ctx.attr(CHANNELID);
		int id = attribute.get();
		buffer.writeInt(id);
		try {
			Dispatcher.receiveBuffers.put(buffer);
		} catch (Exception e1) {
			logger.error("", e1);

		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Attribute<Integer> attribute = ctx.attr(CHANNELID);
		int id = attribute.get();
		try {
			if (Dispatcher.sessionMap.containsKey(id)) {
				new ClearOnlineUserMessage(id).sendToSceneServer();
				Dispatcher.sessionMap.remove(id);
				ctx.channel().close();
			}
		} catch (Exception e1) {
			logger.error("", e1);
		}
	}

}
